package org.yangjie.config.security;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

/**
 * token认证过滤器
 * @author YangJie [2019年1月17日]
 */
@Component
public class TokenAuthenticationFilter extends OncePerRequestFilter{
	
	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, 
			FilterChain filterChain) throws ServletException, IOException {
		
		// 放过登录接口
		if(!"/auth".equals(request.getRequestURI())) {
			String token = request.getHeader("token");
	        SecurityContextHolder.getContext().setAuthentication(new TokenAuthenticationToken(token));
	        // 也可以模拟通过用户名和密码登录成功 
	        // 此处直接获取用户权限信息然后 new UsernamePasswordAuthenticationToken(null, null, authorities)
		}
        filterChain.doFilter(request, response);
        
	}

}
